package com.my.assembly.handler;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.my.assembly.bridge.BridgeHandler;
import com.my.assembly.bridge.CallBackFunction;
import com.my.assembly.config.Config;
import com.my.assembly.entity.AuthResult;
import com.my.assembly.entity.PayResult;
import com.my.assembly.entity.WxResult;
import com.my.assembly.event.WeChatPayEvent;
import com.my.assembly.http.HttpClient;
import com.my.assembly.utils.HandlerUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * <pre>
 *     author : wxq
 *     e-mail :
 *     time   : 2018/11/27
 *     desc   : 支付组件
 *     version: 1.0
 * </pre>
 */
public class PayHandler implements BridgeHandler {

    private IWXAPI api;

    private Activity mContext;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private CallBackFunction mFunction;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        Toast.makeText(UserAccountRechargeActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        success();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(mContext.getApplicationContext(), "支付失败" + resultInfo, Toast.LENGTH_SHORT).show();
                        fail("支付失败");
                    }
                    //TODO 加载结果
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(mContext.getApplicationContext(),
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(mContext.getApplicationContext(),
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
                        fail("授权失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    public PayHandler(Activity context, IWXAPI api) {
        this.mContext = context;
        this.api = api;
    }

    @Override
    public void handler(String data, CallBackFunction function) {
        this.mFunction = function;
        JsonObject jsonObject = (JsonObject) new JsonParser().parse(data);
        String type = jsonObject.get("type").getAsString();
        String orderId = jsonObject.get("orderId").getAsString();
        if ("1".equals(type)) {
            //微信支付
            OkHttpClient client = HttpClient.getInstance().getClient();
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, "orderId=" + orderId);
            Request request = new Request.Builder()
                    .url(Config.base_url + "/WebApp/WechatPay/wx_pay")
                    .post(body)
                    .addHeader("DEVICEINFO", "5sxNE5I4Cacsp9idSA")
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    HandlerUtils.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "请求订单信息出错", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String s = response.body().string();
                    //支付宝支付
                    if (TextUtils.isEmpty(s)) {
                        HandlerUtils.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(mContext, "订单信息为空", Toast.LENGTH_SHORT).show();
                            }
                        });
                        return;
                    }
                    WxResult wxResult = null;
                    try {
                        wxResult = new Gson().fromJson(s, WxResult.class);
                    } catch (Exception e) {
                        HandlerUtils.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(mContext, "服务器返回错误:" + s, Toast.LENGTH_SHORT).show();
                            }
                        });
                        e.printStackTrace();
                    }
                    if (wxResult == null) return;
                    PayReq request = new PayReq();
                    request.appId = wxResult.appid;
                    request.partnerId = wxResult.partnerid;
                    request.prepayId = wxResult.prepayid;
                    request.packageValue = wxResult.packageX;
                    request.nonceStr = wxResult.noncestr;
                    request.timeStamp = String.valueOf(wxResult.timestamp);
                    request.sign = wxResult.sign;
                    api.sendReq(request);
                }
            });
        } else {
            OkHttpClient client = HttpClient.getInstance().getClient();
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, "orderId=" + orderId);
            Request request = new Request.Builder()
                    .url(Config.base_url + "/WebApp/AliPay/appPay")
                    .post(body)
                    .addHeader("DEVICEINFO", "JxRaZezavm3HXM3d9pWnYiqqQC1SJbsU")
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    HandlerUtils.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "请求订单信息出错", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String s = response.body().string().replace("\"", "");
                    //支付宝支付
                    if (TextUtils.isEmpty(s)) {
                        HandlerUtils.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(mContext, "订单信息为空", Toast.LENGTH_SHORT).show();
                            }
                        });
                        return;
                    }
                    final String orderInfo = s;
                    Runnable payRunnable = new Runnable() {

                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(mContext);
                            Map<String, String> result = alipay.payV2(orderInfo, true);
                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };
                    // 必须异步调用
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                }
            });
        }
    }

    public void wechatPayCallback(final WeChatPayEvent weChatPayEvent) {
        // 0成功 ,-1失败, -2取消
        HandlerUtils.post(new Runnable() {
            @Override
            public void run() {
                if (weChatPayEvent.code == 0) {
                    success();
                } else if (weChatPayEvent.code == -1) {
                    fail("失败");
                }
            }
        });
    }

    private void success() {
        if (mFunction != null) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("code", 1);
            jsonObject.addProperty("message", "支付成功");
            mFunction.onCallBack(jsonObject.toString());
        }
    }

    private void fail(String message) {
        if (mFunction != null) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("code", 0);
            jsonObject.addProperty("message", message);
            mFunction.onCallBack(jsonObject.toString());
        }
    }
}
